package com.zeny.express.framework.webapp.interceptor;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import com.zeny.express.framework.core.support.SpringContext;
import com.zeny.express.framework.shared.domain.User;
import com.zeny.express.framework.sso.TokenManager;
import com.zeny.express.framework.webapp.context.UserContext;
import com.zeny.express.framework.webapp.service.WebApplicationManager;

/**
 * 用户权限拦截器
 * 
 * @author zhuwei
 * @date 2013年8月28日 下午12:55:27
 */
public class SecurityInterceptor extends MethodFilterInterceptor {

	/**
	 * 序列号
	 */
	private static final long serialVersionUID = 4778532437078710119L;

	/**
	 * 日志
	 */
	protected static final Logger LOGGER = LoggerFactory
			.getLogger(SecurityInterceptor.class);

	private TokenManager tokenManger;
	
	private WebApplicationManager webApplicationManager;
	
	public void init() {
		
		LOGGER.info("[framework] init security interceptor...");
		
		/*tokenManger = applicationContext.getBean(TokenManager.class);
		String contextPath = ServletActionContext.getServletContext().getContextPath();
		tokenManger.setAppId(contextPath);
		LOGGER.info("init SecurityInterceptor...{}, {}", contextPath, tokenManger);*/
	}
	
	/** 
	 * TODO 
	 * 1)判断用户是否已登录或者会话已过期
	 * 2)获取登录用户权限，拦截访问的页面菜单、按钮点击的提交是否有权限
	 * @author zhuwei
	 * @date 2013年8月28日 下午12:56:03
	 * @see com.opensymphony.xwork2.interceptor.MethodFilterInterceptor#doIntercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		
		if (tokenManger == null) {
			tokenManger = SpringContext.getBean(TokenManager.class);
			String contextPath = ServletActionContext.getServletContext().getContextPath();
			tokenManger.setAppId(contextPath);
//			tokenManger.resolveUserId(tokenId)
			
			LOGGER.info("[framework] init SecurityInterceptor...{}, {}", contextPath, tokenManger);
		}
		
		if (webApplicationManager == null) {
			webApplicationManager = SpringContext.getBean(WebApplicationManager.class);
		}
		
		User user = webApplicationManager.getUserByCode(null);
		UserContext.setCurrentUser(user);
		
		try {

			return invocation.invoke();
		} finally {
			UserContext.clear();
		}
	}

}
